const env = require('./config.js');
const base64 = require('./base64.js');
require('./hmac.js');
require('./sha1.js');
const Crypto = require('./crypto.js');
import moment from 'moment';


const getPolicyBase64 = function () {
  let date = new Date();
  date.setHours(date.getHours() + env.timeout);
  let srcT = date.toISOString();
  const policyText = {
    "expiration": srcT, //设置该Policy的失效时间，超过这个失效时间之后，就没有办法通过这个policy上传文件了 
    "conditions": [
      ["content-length-range", 0, env.maxSize] // 设置上传文件的大小限制,5mb
    ]
  };

  const policyBase64 = base64.encode(JSON.stringify(policyText));
  return policyBase64;
}


function izArrayBufferToBase64(buffer) {
  var binary = '';
  var bytes = new Uint8Array(buffer);
  var len = bytes.byteLength;
  for (var i = 0; i < len; i++) {
    binary += String.fromCharCode(bytes[i]);
  }
  let signature = base64.encode(binary)
  return signature
}


const getSignature = function (policyBase64) {
  const accesskey = env.AccessKeySecret;
  const bytes = Crypto.HMAC(Crypto.SHA1, policyBase64, accesskey, {
    asBytes: true
  });
  const signature = izArrayBufferToBase64(bytes)
  return signature;
}

export function getFormData () {
  let path = moment().format("YYYY-MM-DD")
  //存放文件命名格式：自定义时间戳给文件名字(可以自己改)
  const aliyunFileKey = path + '/' + new Date().getTime() + parseInt(Math.random() * (9999 - 1000 + 1) + 1000,
    10)

  const aliyunServerURL = env.uploadImageUrl; //OSS地址，https
  const accessid = env.OSSAccessKeyId;
  let policyBase64 = getPolicyBase64();
  let signature = getSignature(policyBase64);

  return {
    'key': aliyunFileKey,
    'policy': policyBase64,
    'OSSAccessKeyId': accessid,
    'signature': signature,
    'success_action_status': '200',
  }
}


export default {
  getSignature,
  izArrayBufferToBase64,
  getPolicyBase64,
}
